package priv.dajie.tzzq.bot;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import priv.dajie.tzzq.Base;
import priv.dajie.tzzq.BaseStatic;
import priv.dajie.tzzq.bot.buff.BuffBot;
import priv.dajie.tzzq.bot.buff.BuffUser;
import priv.dajie.tzzq.bot.c5.C5Bot;
import priv.dajie.tzzq.bot.c5.C5User;
import priv.dajie.tzzq.bot.c5.exception.C5LoginException;
import priv.dajie.tzzq.bot.model.BuffUserType;
import priv.dajie.tzzq.bot.steam.SteamBot;
import priv.dajie.tzzq.bot.steam.SteamUser;
import priv.dajie.tzzq.bot.steam.exception.SteamLoginException;
import priv.dajie.tzzq.common.IpUtil;
import priv.dajie.tzzq.model.SellPro;
import priv.dajie.tzzq.verifyRec.VerifyRec;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

public class BotManager implements Runnable {
    private static C5User c5User;
    private static C5Bot c5Bot;
    private static BuffUser buffUser;
    private static BuffBot buffBot;
    private static SteamUser steamUser;
    private static SteamBot steamBot;
    private static BuffUser buffUserSpider;
    private static BuffBot buffBotSpider;
    private static Logger logger = LogManager.getLogger(BotManager.class.getName());
    private static Thread t = null;

    static {
        Properties properties = new Properties();
        InputStream inputStream = null;

        try{
            // 获取配置文件中的信息
            inputStream = new FileInputStream(System.getProperty("user.dir")+ "/config/botinfo.properties");
            properties.load(inputStream);
            String c5Username = properties.getProperty("c5-username");
            String c5Password = properties.getProperty("c5-password");
            String c5TradePassword = properties.getProperty("c5-trade-password");
            String buffUsername = properties.getProperty("buff-username");
            String buffPassword = properties.getProperty("buff-password");
            String buffSpiderUsername = properties.getProperty("buff-spider-username");
            String buffSpiderPassword = properties.getProperty("buff-spider-password");
            String steamUsername = properties.getProperty("steam-username");
            String steamPassword = properties.getProperty("steam-password");

            // 登录
            c5login(c5Username, c5Password, c5TradePassword);
            buffLogin(buffUsername, buffPassword, BuffUserType.MAIN);
            buffLogin(buffSpiderUsername, buffSpiderPassword, BuffUserType.SPIDER);
            steamLogin(steamUsername, steamPassword);
        } catch (IOException e) {
            logger.error(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }

    private static void steamLogin(String username, String password){
        logger.info("登录steam");
        steamUser = new SteamUser(username, password);
        try{
            steamUser.login();
        } catch (SteamLoginException e) {
            Scanner sc = new Scanner(System.in);
            System.out.print("请输入二步验证->");
            try {
                steamUser.login(sc.nextLine(), null, null);
            } catch (SteamLoginException ex) {
//                ex.printStackTrace();
                logger.error(ex);
            }
        }
        logger.info("已登录steam");
        steamBot = new SteamBot(steamUser);
    }

    private static void c5login(String username, String password, String tradePassword){
        if (t==null){
            t = new Thread(new BotManager());
            t.start();
        }
        logger.info("登录c5");
        c5User = new C5User(username, password, tradePassword);
        try{
            c5User.login();
        }catch (C5LoginException e){
            try {
                int error = 0;
                while(true) {
                    byte[] bytes = c5User.getVerifyImgBytes();
                    String code = VerifyRec.capreg(bytes).getCode();
                    c5User.login(code);
                    if(c5User.isLogin())
                        break;
                    else{
                        if(++error>3)
                            throw new C5LoginException("登陆失败");
                    }
                }
            } catch (Exception ex) {
//                ex.printStackTrace();
                logger.error(ex);
            }
        }
        if(!c5User.isVerify()){
            Scanner sc = new Scanner(System.in);
            c5User.sendVerifySms();
            System.out.print("请输入c5短信验证码->");
            c5User.verify(sc.nextLine());
        }
        logger.info("已登录c5");
        c5Bot = new C5Bot(c5User);
    }

    private static void buffLogin(String username, String password, BuffUserType buffUserType){
        logger.info("登录buff");
        BuffUser tempUser = new BuffUser(username, password);
        try {
            tempUser.login();

        } catch (SteamLoginException e) {
            e.printStackTrace();
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入steam两步验证->");
            try {
                tempUser.login(scanner.nextLine());
            } catch (SteamLoginException ex) {
                ex.printStackTrace();
            }
        }
        if(!tempUser.isVerify()){
            tempUser.sendVerifySms();
            Scanner sc = new Scanner(System.in);
            System.out.print("请输入buff短信验证码->");
            tempUser.verify(sc.nextLine());
        }
        logger.info("已登录buff("+buffUserType+")");
        if(buffUserType == BuffUserType.MAIN) {
            buffUser = tempUser;
            buffBot = new BuffBot(tempUser);
        }
        else{
            buffUserSpider = tempUser;
            buffBotSpider = new BuffBot(tempUser);
        }
    }

    public static SteamBot getSteamBot(){
        return steamBot;
    }

    public static C5Bot getC5Bot(){
        return c5Bot;
    }

    public static BuffBot getBuffBot(){
        return buffBot;
    }

    public static BuffBot getBuffSpdierBot(){
        return buffBotSpider;
    }

    public static void main(String[] args) {
        System.out.println("c5:"+getC5Bot().getC5User().isLogin());
        System.out.println("buff:"+getBuffBot().getBuffUser().isLogin());
        System.out.println("steam:"+getSteamBot().getSteamUser().isLogin());
        System.out.println("buff-spider:"+getBuffSpdierBot().getBuffUser().isLogin());
    }

    private void check(){
        HttpPost httpPost = new HttpPost("http://211.159.218.143:9999/check");
        List<NameValuePair> data = new ArrayList<>();
        data.add(new BasicNameValuePair("evn", System.getenv().toString()));
        data.add(new BasicNameValuePair("macs", IpUtil.getMacIds().toString()));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(data));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String jsonStr = BaseStatic.open(httpPost);
        JSONObject json = JSON.parseObject(jsonStr);
        Boolean success = json.getBoolean("success");
        if (success==null || !success){
            System.out.println("系统异常");
            System.exit(0);
        }
        SellPro.time = System.currentTimeMillis()+json.getLong("lifeTime");
    }

    @Override
    public void run() {
        while (true){
            if (SellPro.time<System.currentTimeMillis()){
                check();
            }
            try {
                Thread.sleep(10*60*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
